<template>
  <view class="containt">
    <view class="cardbox">
      <view class="flexCenterSpaceBetween mb20">
        <view class="title">选择类别</view>
          <view class="flex flexYCenter">
            <view class="info">闲置商品接收标准</view>
            <u-icon color="#999999" size="28" name="error-circle"></u-icon>
          </view>
      </view>
      <view class="typecardbox">
        <view
					v-for="item in typelist1"
          :class="{ targetactive: activetype == item.name }"
          class="flexCenterCenter typecard"
          ::key="item"
					@tap="handleChangeType(item)"
        >
          <image
            class="yuanimg"
            src="@/static/img/sale1.png"
            mode="widthFix"
          >
          </image>
          <view class="yuantext">{{ item.name }}</view>
        </view>
      </view>
    </view>
    <view class="cardbox">
      <view class="title mb20">所属品牌</view>
      <view class="flex">
        <view class="targettab targettabbg flexCenterCenter" v-if="isselpinpai">
          <image
            class="yuanimg"
            :src="`${baseimgURL}${selpinpai.brandLogo}`"
            mode="widthFix"
          ></image>
          <text class="">{{selpinpai.brandName}}</text>
        </view>
        <view
          class="targettab flexCenterCenter"
          @tap="jumppage('/pages/sale/selectpai')"
        >
          <image
            class="pingpaiimg"
            src="@/static/img/sale2.png"
            mode="widthFix"
          ></image>
          <view class="flex"
            >全部品牌
            <u-icon name="arrow-right"></u-icon>
          </view>
        </view>
      </view>
    </view>
    <view class="cardbox">
      <view class="title mb20">商品图片</view>
      <view class="flex flexupload">
        <view v-if="!isAuth" class="upload-layer" @tap="handleClickLayer"></view>
        <view class="upload-container">
          <view class="photobox" v-for="(item, idx) in picList" ::key="item">
            <u-upload
              :fileList="state['fileList' + idx]"
              @afterRead="afterRead($event, idx)"
              @delete="deletePic($event, idx)"
              name="file"
              :maxCount="1"
              width="155"
              height="155"
            >
              <view class="photocard">
                <image
                  class="photoimg"
                  mode="widthFix"
                  :src="`${baseimgURL}${item.imgUrl}`"
                >
                </image>
                <view class="mt10 describe">{{item.label}}</view>
              </view>
            </u-upload>
          </view>
        </view>
      </view>
    </view>
    <view class="cardbox">
      <view class="title mb20">商品成色</view>
      <view class="flex chengseflexbox">
        <view
          class="chengsebox"
          @tap="handletype2(item)"
          :class="{ targetactive: activetarget == item }"
          v-for="item in typelist"
          ::key="item"
        >
          <view>{{ item.title }}</view>
          <view style="font-size: 22rpx;">{{ item.name }}</view>
        </view>
      </view>
    </view>
    <view class="cardbox flexYCenter"  style="margin-bottom: 60rpx;">
      <view class="title mb20">备注说明</view>
      <u-textarea
        v-model="description"
        placeholder="备注需要补充的说明"
        ref="textarea"
      ></u-textarea>
    </view>
		<!-- 吸底工具栏 -->
		<view class="flex " style="width: 100%;height: 90rpx;background: #fff;position: fixed;left: 0;bottom: 100rpx;font-size: 22rpx;padding-left: 34rpx;display: flex;align-items: center">
			<checkbox-group @change="handleYes($event)" style="">
				<label>
					<checkbox value="isConsent.value" checked="true" style="transform:scale(0.7)" />使用即表示同意
				</label>
			</checkbox-group>
			<text style="font-weight: 600;" @click="clickViewProtocol('/pages/me/mine')">《奢收多卖家回收协议》</text>
		</view>
        <view
        class="toolbar-height"
        :style="{ paddingBottom: safeAreaInsets?.bottom+30 + 'px' }"
      ></view>
      <view
        class="toolbar"
        :style="{ paddingBottom: safeAreaInsets?.bottom +30+ 'px' }"
      >
		<view class="button-grounp">
		  <view @tap="submit" class="button payment-button" style="width: 720rpx;">
			<view class="title">提交评估</view>
		  </view>
		</view>
      </view>
    <gorenzheng ref="renRef" @gorenpage="gorenpage"></gorenzheng>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, inject } from "vue"
import { uploadAction } from '../../config/index'
import ORDERCONSTANT from '../../constant/order'
import { createOrder, fetchConfigList } from '../../api/order'
import { baseimgURL } from '@/config'
import { getAuthStatus } from '@/utils/common'
import gorenzheng from "@/components/gorenzheng"

const activetype = ref('')
const activetarget = ref("")
const isConsent = ref(true)
const isselpinpai = ref(false)
const selpinpai = ref(null)
const description = ref('')
const picListLen = ref(9)
const picList = ref([])
const isAuth = ref(false)
const renRef = ref(null)

const handleYes = () => {
  isConsent.value = !isConsent.value;
}
const handletype2 = (item) => {
  activetarget.value = item;
}
const state = reactive({
	fileList0: [],
	fileList1: [],
	fileList2: [],
	fileList3: [],
	fileList4: [],
	fileList5: [],
	fileList6: [],
	fileList7: [],
	fileList8: [],
})

// 删除图片
const deletePic = (event, index) => {
	state['fileList' + index] = []
}

// 新增图片
const afterRead = async (event, index) => {
	const fList = state['fileList' + index]
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = fList.length;
  lists.map((item) => {
    fList.push({
      ...item,
      status: "uploading",
      message: "上传中",
    })
  })
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url)
    let item = fList[fileListLen]
    fList.splice(fileListLen, 1, {
      ...item,
      status: "success",
      message: "",
      url: `${baseimgURL}${result.data.url}`,
    });
    fileListLen++;
  }
}

const uploadFilePromise = (url) => {
	const token = uni.getStorageSync("token")
	const token_type = uni.getStorageSync("token_type")
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: uploadAction,
      filePath: url,
      name: "file",
			header: {
				"content-type": "application/json",
				"Authorization": `${token_type} ` + `${token}`,
			},
			formData: {
				typeCode: 'RecycleOrder',
				fieldProperty: 'productPicture',
			},
      success: (res) => {
				const data = JSON.parse(res.data)
				resolve(data)
      },
    });
  });
}
const clickViewProtocol = (url) => {
	let allAgreement = JSON.parse(uni.getStorageSync('allAgreement'))
	uni.navigateTo({ url: url+'?id='+ allAgreement[2].value.id+'&title='+'奢收多卖家回收协议'});
}
const jumppage = (url) => {
  uni.navigateTo({ 
		url: url,
		events: {
			// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
			acceptDataFromOpenedPage: function(data) {
				if(data){
					isselpinpai.value = true
					console.info('已选择品牌: ', JSON.parse(data.data))
					selpinpai.value = JSON.parse(data.data)?.item ?.name
				}
			},
		},
	})
}
const typelist1 = ORDERCONSTANT.GOODS_CATEGORY
const typelist = ref([
  { title: "全新", name: "未使用或未拆封" },
  { title: "轻微使用", name: "无磨损无瑕疵" },
  { title: "大量使用", name: "有污渍、划痕、磨损" },
  { title: "损坏", name: "已损坏、部分损坏" },
])

const handleChangeType = async (item) => {
	activetype.value = item.name
	try {
		const { code, msg, data } = await fetchConfigList([item.value])
		if (code === '1') {
			const content = JSON.parse(data[0].configContent)
			picListLen.value = content.length
			picList.value = content
		} else {
			uni.showToast({
				title: msg,
				icon: 'none'
			})
		}
	} catch(err) {
		console.error(err)
	}
}

// 去认证
const gorenpage = () => {
  uni.navigateTo({
    url: "/pages/me/authentication",
  })
}

const handleClickLayer = () => {
  renRef.value.maopen();
}

const submit = async () => {
  try {
		if (!activetype.value) {
			uni.showToast({
				title:'请选择类别',
				icon:'none'
			})
			return
		}
		if (!selpinpai.value) {
			uni.showToast({
				title:'请选择品牌',
				icon:'none'
			})
			return
		}
		if (!activetarget.value) {
			uni.showToast({
				title:'请选择商品成色',
				icon:'none'
			})
			return
		}
		const fileList = []
		for (let key in state) {
			if (state[key] && state[key][0]) {
        fileList.push(state[key][0].url.replace(`${baseimgURL}/`, '/'))
			}
		}
		if (fileList.length > 2) {
			const params = {
			  typeCode: 'RecycleOrder',
			  form: {
			    category: activetype.value, // 品类
			    brandId: selpinpai.value?.id, // 品牌
			    productPicture: fileList.join(','), // 图片
			    fineness: activetarget.value?.title, // 成色
			    description: description.value, // 商品描述
			  }
			}
			const { code, msg } = await createOrder(params)
			if (code === '1') {
			  uni.showToast({ icon: "success", title: '创建成功' })
				setTimeout(() => {
          uni.navigateTo({ url: '/pages/orderPage/orderPage' })
				}, 1000)
			} else {
			  uni.showToast({ icon: "none", title: msg })
			}
		} else {
			uni.showToast({ icon: "none", title: '请上传完整商品图片' })
		}
  } catch(err) {
    console.error(err)
  }
}

onMounted(() => {
  isAuth.value = getAuthStatus()
	handleChangeType({name: '箱包', value: 'xiangbao_recyle'})
})
</script>

<style lang="scss" scoped>
.containt {
  padding: 15rpx 22rpx;
}
.button-grounps{
	display: flex;
	justify-content: center;
	text-align: center;
	height: 85rpx;
	font-size: 13px;
	color: #fff;
	.button {
	  width: 720rpx;
	  margin: 0 10rpx;
	  border-radius: 72rpx;
	  padding: 10rpx 0rpx;
	}
	.payment-button {
	  background: #953b82;
	  border-radius: 8rpx;
	  .title{
		  font-size: 27rpx;
		  font-weight: 600;
	  }
	  .describe{
		  font-size: 22rpx;
		  font-weight: 400;
		  opacity: .4;
	  }
	}
}

.cardbox {
  background: #ffffff;
  border-radius: 14rpx;
  padding: 22rpx;
  margin-bottom: 15rpx;
  .info{
	  font-size: 24rpx;
	  font-family: PingFangSC, PingFang SC;
	  font-weight: 400;
	  color: #666666;
	  line-height: 33rpx;
	  margin-right: 7rpx;
  }
  .title {
    font-size: 27rpx;
    font-weight: 600;
    color: #000000;
  }

  .typecardbox {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    /* justify-content: space-between; */
    /* &::after {
      content: "";
      width: calc(25% - 15rpx);
    } */
    .typecard {
      border-radius: 7rpx;
      border: 2rpx solid #e6e6e6;
      text-align: center;
      width: calc((100% - 60rpx) / 4);
      margin-right: 20rpx;
      margin-bottom: 10rpx;
      padding: 5rpx 0;
      box-sizing: border-box;
      &:nth-child(4n + 4) {
        margin-right: 0;
      }
    }

    .yuantext {
      white-space: nowrap;
	  font-size: 24rpx;
	  font-weight: 400;
	  color: #333333;
	  line-height: 33rpx;
    }
  }
  .yuanimg {
    width: 52rpx;
    height: 52rpx;
    border-radius: 33rpx;
    margin-right: 13rpx;
  }
  .pingpaiimg {
    width: 52rpx;
    height: 52rpx;
    border-radius: 33rpx;
    margin-right: 13rpx;
    margin-left: -40rpx;
    border: 2rpx solid #e6e6e6;
  }
  .noselectpingpaiimg {
    width: 52rpx;
    height: 52rpx;
    border-radius: 33rpx;
    margin-right: 13rpx;
    border: 2rpx solid #e6e6e6;
  }
  .targettab {
    flex: 1;
    height: 63rpx;
    border-radius: 7rpx;
    border: 2rpx solid #e6e6e6;
    font-size: 22rpx;
    font-weight: 400;
  }
  .targettabbg {
    background: #f6edf4;
    color: #953b82;
  }
  .notargettab {
    padding: 11rpx;
  }
  .targetactive {
    background: #f6edf4;
    color: #953B82;
  }
  .targettab:nth-child(1) {
    margin-right: 20rpx;
  }
  .flexupload {
    position: relative;
  }
  .upload-container {
    display: flex;
    flex-wrap: wrap;
  }
  .flexupload .upload-layer {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 999;
  }
  .photobox {
    width: calc((100% - 60rpx) / 4);
    margin-right: 20rpx;
    box-sizing: border-box;
    margin-top: 20rpx;
	  margin-bottom: 10rpx;
    &:nth-child(4n + 4) {
      margin-right: 0;
    }
    .photoimg {
      width: 73rpx;
      height: 73rpx;
    }
    .photocard {
      width: 155rpx;
      height: 155rpx;
      background: #f0f0f0;
      border-radius: 7rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-direction: column;
	  padding-top: 47rpx;
	  box-sizing: border-box;
	  .describe{
		  font-size: 24rpx;
		  color: #ffffff;
		  width: 100%;
		  text-align: center;
		  height: 38rpx;
		  background: linear-gradient(180deg, rgba(255,255,255,0) 0%, rgba(0,0,0,0.8) 100%);
		  opacity: .4;
	  }
    }
  }
  .chengseflexbox {
    flex-wrap: wrap;
    .chengsebox {
      margin-right: 15rpx;
      width: calc((100% - 15rpx) / 2);
      height: 118rpx;
      vertical-align: middle;
      border-radius: 7rpx;
      border: 2rpx solid #e6e6e6;
      box-sizing: border-box;
      margin-bottom: 13rpx;
      padding: 22rpx;
      &:nth-child(2n) {
        margin-right: 0;
      }
	  .chengseTitle{
		  color: #666666;
		  font-weight: 600;
		  font-size: 25rpx;
		  margin-bottom: 7rpx;
	  }
	  .chengseDescription{
		  color: #666666;
		  font-size: 25rpx;
	  }
    }
  }
}
.moneytext {
  font-size: 24rpx;
  font-weight: 600;
  color: #e6542b;
}
</style>
